"use strict";

const axios = require("axios");
const urlJoin = require("url-join");

const semver = require("semver");

const npmregistry = "https://registry.npmjs.org";
const cnpmregistry = "https://registry.npmmirror.com";
// 请求
function getNpmInfo(namName, registry) {
  if (!namName) return null;

  const registryUrl = registry || getDefaultRegistry();

  const npmInfoUrl = urlJoin(registryUrl, namName);
  // console.log("🚀 ~ getNpmInfo ~ npmInfoUrl:", npmInfoUrl);
  return axios
    .get(npmInfoUrl)
    .then((res) => {
      if (res.status === 200) {
        return res.data;
      }
      return null;
    })
    .catch((err) => {
      return Promise.reject(`${namName}没有这个包`);
    });
}

// 获取默认 registry
function getDefaultRegistry(isOriginal = false) {
  return !isOriginal ? npmregistry : cnpmregistry;
  // : "https://registry.npm.taobao.org";
}

// 获取 npm 版本，处理
async function getNpmVersions(namName, registry) {
  const data = await getNpmInfo(namName, registry);
  if (data) {
    const versions = data.versions;
    return Object.keys(versions);
  } else {
    return [];
  }
}

// 版本号比对
function getSemverVersions(baseVersion, versions) {
  versions = versions
    .filter((version) => semver.satisfies(version, "^" + baseVersion))
    .sort((a, b) => {
      return semver.lt(a, b) ? 1 : -1;
    });

  return versions;
}

async function getNpmSemverVersions(baseVersion, namName, registry) {
  const versions = await getNpmVersions(namName, registry);
  const newVersion = getSemverVersions(baseVersion, versions);
  return (newVersion.length && newVersion[0]) || null;
}

// 获取最新版本
async function getNpmLatestVersion(namName, registry) {
  const versions = await getNpmVersions(namName, registry);
  if (versions) {
    return versions.sort((a, b) => (semver.lt(a, b) ? 1 : -1))[0];
  }
  return null;
}

module.exports = {
  getNpmInfo,
  getNpmVersions,
  getNpmSemverVersions,
  getDefaultRegistry,
  getNpmLatestVersion,
};
